package com.rp.system.controller;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageData;
import com.rp.controller.RpController;
import com.rp.system.po.User;
import com.rp.system.service.RoleService;
import com.rp.system.service.UserService;
import com.rp.system.vo.UserVo;

@Controller
@RequestMapping("/rp/system/userMng/")
public class UserController extends RpController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	
	@RequestMapping("showUserGrid")
	public ModelAndView showUserGrid(){
		
		return forward("/rp/system/userMng/userGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getUsers")
	public PageData getUsers(UserVo userVo){
		PageData pd = new PageData(userService.getUserDao().getUsersByPage(pageParam, userVo));
		return pd;
	}
	
	@ResponseBody
	@RequestMapping("getAllUsers")
	public List<User> getAllUsers(){
		List<User> users = userService.getUserDao().find("from User");
		return users;
	}
	
	@ResponseBody
	@RequestMapping("getUseraByOrganId")
	public List<User> getUseraByOrganId(String organId){
		List<User> users = userService.getUserDao().find("from User where organId = ?", organId);
		return users;
	}
	
	@ResponseBody
	@RequestMapping("saveUsers")
	public String saveUsers(String data){
		try {
			List<User> users = JsonUtil.jsonToList(data, "com.rp.system.po.User");
			for (User user : users) {
				if(user.getId() == null){
					userService.addUser(user);
				}else{
					userService.updateUser(user);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteUsers")
	public String deleteUsers(String data){
		try {
			List<User> users = JsonUtil.jsonToList(data, "com.rp.system.po.User");
			for (User user : users) {
				userService.deleteUser(user.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("resetPasswords")
	public String resetPasswords(String data){
		try {
			List<User> users = JsonUtil.jsonToList(data, "com.rp.system.po.User");
			for (User user : users) {
				userService.resetPassword(user.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return SUCCESS;
	}
	
	@RequestMapping("showChangePwdWindow")
	public ModelAndView showChangePwdWindow(@RequestParam(required=true) String userId){
		model.put("userId", userId);
		return forward("/rp/system/userMng/changePwdWindow.jsp");
	}
	
	@ResponseBody
	@RequestMapping("changePwd")
	public String changePwd(String json){
		Map<String, Object> data = JsonUtil.jsonToMap(json);
		String originalPwd = (String) data.get("originalPwd");
		String userId = (String) data.get("userId");
		String newPwd = (String) data.get("newPwd");
		String newPwd2 = (String) data.get("newPwd2");
		try {
			if(!newPwd.equals(newPwd2)){
				return "请确认您两次输入的密码是相同的";
			}
			userService.changePassword(userId, originalPwd, newPwd2);
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	@ResponseBody
	@RequestMapping("getCurrentUserHeadImg")
	public String getCurrentUserHeadImg(){
		
		User user = User.getCurrentUser();
		if(!RpUtil.isNullOrEmpty(user)){
			User dbUser = userService.getUserDao().get(user.getId());
			if(dbUser.getHeadImg() != null && !dbUser.getHeadImg().equals("")){
				return dbUser.getHeadImg();
			}else{
				return ERROR;
			}
		}
		
		return ERROR;
	}
	
	/**
	 * 上传头像
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("uploadHeadImg")
	public String uploadHeadImg(@RequestParam MultipartFile file){
		String saveDirectory = this.getWebServerDirectory()+"/headImgDirectory/";
		String fileName = file.getOriginalFilename();
		String suffix = RpUtil.cutFileSuffixName(fileName);
		String newFileName = RpUtil.createGuid()+suffix;
		File targetFile = new File(saveDirectory, newFileName);
		//如果目录不存在则创建目录
        if(!targetFile.exists()){  
            targetFile.mkdirs();
        }
        //保存文件至服务器中
        try {  
            file.transferTo(targetFile);
            
        	userService.updateUserHeadImg(User.getCurrentUser().getId(), "headImgDirectory/"+newFileName);
        } catch (Exception e) {  
            e.printStackTrace();
            return "图片上传失败，请重新上传";
        } finally {
        	
        }
		
		return "图片上传成功，关闭窗口即可生效";
	}
	
}
